package com.capt_4.io;

import com.capt_4.equation.AddEquation;
import com.capt_4.equation.Equation;
import com.capt_4.Exercise;
import com.capt_4.equation.SubEquation;

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public class EquationDao {
    // 将习题集中的题目写入文本文件。
    public static void writExerciseToFile(Exercise ex,String filepath) throws IOException {
        System.out.println(filepath);
        File file = new File(filepath);

        // 创建字符流（输出流）
        FileWriter fw = null;
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
//        fw = new FileWriter(filepath);
        fw = new FileWriter(file);
        try {
//            fw = new FileWriter(file);
            ArrayList<Equation> list = ex.getList();
            for (int i=0;i<list.size();i++){
                Equation equation = list.get(i);
                String string = equation.toString();
                System.out.println(string);
                // 将文件写入到文件中
                fw.write(string+",");
                fw.flush();
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
//                oos.close();
                fw.close();
//                fos.close();
            } catch (IOException e){
                e.printStackTrace();
            }

        }

    }


    // 读取文件，将字符串解析为对应的加减方
    public static Exercise readExerciseFromFile(String filePath){
        File file = new File(filePath);

        Exercise exercise = new Exercise();
        //  创建输入流
        Scanner scanner = null;
        try {
            scanner = new Scanner(file);
            // 指定输入流读取规则
            scanner.useDelimiter(",");
//            System.out.println("习题集输出打印测试：");
            while (scanner.hasNext()){
                String equationString = scanner.next();
//                System.out.println(equationString);
                if (equationString.contains("+")){
                    AddEquation addEquation = new AddEquation(equationString);
                    exercise.getList().add(addEquation);
                } else if (equationString.contains("-")){
                    SubEquation subEquation = new SubEquation(equationString);
                    exercise.getList().add(subEquation);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println(exercise);
        return exercise;
    }


}
